package com.zjsru.plan2024.normal;

/**
 * 1017. 负二进制转换
 * @Author: cookLee
 * @Date: 2024-05-04
 */
public class BaseNeg2 {

    /**
     * 主
     * \
     * 输入：n = 2
     * 输出："110"
     * 解释：(-2)2 + (-2)1 = 2
     * \
     * 输入：n = 3
     * 输出："111"
     * 解释：(-2)2 + (-2)1 + (-2)0 = 3
     * \
     * 输入：n = 4
     * 输出："100"
     * 解释：(-2)2 = 4
     * \
     * @param args args
     */
    public static void main(String[] args) {
        BaseNeg2 baseNeg2 = new BaseNeg2();
        int n = 2;
        System.out.println(baseNeg2.baseNeg2(n));
    }

    /**
     * 负二进制
     *
     * @param n n
     * @return {@link String}
     */
    public String baseNeg2(int n) {
        if (n == 0) {
            return "0";
        }
        int k = 1;
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            if (n % 2 != 0) {
                sb.append(1);
                //-2的幂进一位符号会变
                n -= k;
            } else {
                sb.append(0);
            }
            //更新符号
            k *= -1;
            //更新n
            n /= 2;
        }
        return sb.reverse().toString();
    }

}
